package util

import (
"client/services"
"context"
"fmt"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/sd"
"github.com/go-kit/kit/sd/consul"
"github.com/go-kit/kit/sd/lb"
kitHttp "github.com/go-kit/kit/transport/http"
consulApi "github.com/hashicorp/consul/api"
"io"
"net/url"
"os"
"time"
)

func GetUser() (string, error) {
	// 1.定义配置执行，创建consul客户端
	config := consulApi.DefaultConfig()
	config.Address = "http://127.0.0.1:8500" // 注册中心地址
	configClient, err := consulApi.NewClient(config)
	if err != nil {
		return "", err
	}
	client := consul.NewClient(configClient)

	// 2.创建实例
	logger := log.NewLogfmtLogger(os.Stdout)
	// 设置要调用的服务
	instancer := consul.NewInstancer(client, logger, "userService", []string{"primary"}, true)

	// 3.获取端点，注册调用方法
	endpointer := sd.NewEndpointer(
		instancer,
		func(serviceUrl string) (endpoint.Endpoint, io.Closer, error) {
			tart, _ := url.Parse(fmt.Sprintf("https://%s", serviceUrl)) // 127.0.0.1:8080 真实的服务端地址
			return kitHttp.NewClient("GET", tart, services.GetUserInfoRequest, services.GetUserInfoResponse).Endpoint(), nil, nil
		},
		logger,
	)

	// endpoints, _ := endpointer.Endpoints()
	// fmt.Println(len(endpoints))

	// 4.执行调用
	// mylb := lb.NewRoundRobin(endpointer) // 使用轮循算法
	mylb := lb.NewRandom(endpointer, time.Now().Unix()) // 使用随机算法，参数二：随机因子
	//getUserInfo := endpoints[0]
	getUserInfo, getUserInfoErr := mylb.Endpoint()
	if getUserInfoErr != nil {
		fmt.Println("getUserInfoErr", getUserInfoErr)
		return "", getUserInfoErr
	}
	res, resErr := getUserInfo(context.Background(), services.UserRequest{
		Uid: 101,
	})
	if resErr != nil {
		fmt.Println("resErr", resErr)
		return "", resErr
	}
	// 断言转换
	userResponse := res.(services.UserResponse)
	//fmt.Println(userResponse.Result)
	return userResponse.Result, nil
}

